package com.sakura.回溯;

import java.util.ArrayList;
import java.util.List;

public class Code39_组合总和 {

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> ans = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        backTracking(candidates, target, 0, 0);
        return res;
    }

    private void backTracking(int[] candidates, int target, int sum, int start) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            res.add(new ArrayList<>(ans));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            sum += candidates[i];
            ans.add(candidates[i]);
            backTracking(candidates, target, sum, i);
            sum -= candidates[i];
            ans.remove(ans.size() - 1);
        }
    }
}
